package student

import (
	"data/config"
	"data/view/auth"
	"data/view/auth/auth_const"
	"data/view/common"
	"data/view/oauth2"
	"data/view/user"
	"public/message"
	"public/mysqldb"
	"public/tools"

	"github.com/ant0ine/go-json-rest/rest"
)

//学生信息录入
func Add(w rest.ResponseWriter, r *rest.Request) {
	var req StudentInfo
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Teacher, req.Name, req.Nation, req.Birth, req.Province,
		req.City, req.Region, req.Addr, req.Id_card, req.Phone, req.Education, req.Graduate_province, req.Graduate_city,
		req.Graduate_region, req.Graduate_name) || len(req.Family) == 0 || req.Sex == 0 {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var tmp user.User_tbl
	orm.Where("user = ? and business_role = ?", req.Teacher, auth_const.R_4).Find(&tmp)
	if tmp.Id == 0 {
		w.WriteJson(message.GetErrorMsg(message.NotFindError, "招生老师未找到"))
		return
	}
	var info Student_info_tbl
	orm.Where("id_card = ?", req.Id_card).Find(&info)

	if info.Id > 0 && info.Status == 1 {
		w.WriteJson(message.GetErrorMsg(message.ExistedError, "您的信息已通过审核,请勿重复提交"))
		return
	}

	//获取的时候指定外键
	orm.Where("id_card = ?", req.Id_card).Model(&info).Related(&info.User_info_tbl, "User_info_id") //外键关联
	//orm需配置外键

	info.Id_card = req.Id_card
	info.User_info_tbl.Name = req.Name
	info.User_info_tbl.Sex = req.Sex
	info.User_info_tbl.Nation = req.Nation
	info.User_info_tbl.Birth = req.Birth
	info.User_info_tbl.Addr = req.Addr
	info.User_info_tbl.Id_card = req.Id_card
	info.User_info_tbl.Phone = req.Phone
	info.User_info_tbl.Education = req.Education
	info.Province = req.Province
	info.City = req.City
	info.Region = req.Region
	info.Graduate_province = req.Graduate_province
	info.Graduate_city = req.Graduate_city
	info.Graduate_region = req.Graduate_region
	info.Graduate_name = req.Graduate_name
	info.Family_info = tools.GetJsonStr(req.Family)
	info.Teacher = req.Teacher
	info.Id_card = req.Id_card
	info.Attach_json = "{}"
	if orm.Save(&info).Error != nil {
		w.WriteJson(message.GetErrorMsg(message.ExistedError))
		return
	}

	w.WriteJson(message.GetSuccessMsg())
}

//查看自己招生的学生信息
func GetAll(w rest.ResponseWriter, r *rest.Request) {
	var req GetAllParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := auth.CheckRoleAuth(u.Business_role, auth_const.M_2, auth_const.L_A, auth_const.L_B, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	var result []AllReturn
	wait_s := AllReturn{Status: "待审核"}
	pass_s := AllReturn{Status: "已通过"}
	refuse_s := AllReturn{Status: "未通过"}

	wait, pass, refuse := GetStudentsRetStatus(username)
	wait_s.Students = wait
	pass_s.Students = pass
	refuse_s.Students = refuse

	result = append(result, wait_s, pass_s, refuse_s)
	msg := message.GetSuccessMsg(message.NormalMessageId)
	msg.Data = result
	w.WriteJson(msg)

}

//学生信息审核
func Verify(w rest.ResponseWriter, r *rest.Request) {
	var req VerifyParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token, req.Id_card) || req.Result == 0 {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := auth.CheckRoleAuth(u.Business_role, auth_const.M_2, auth_const.L_A, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	//验证是否招生老师是否为自己
	var student Student_info_tbl
	orm.Where("id_card = ?", req.Id_card).Find(&student)
	if student.Id == 0 || student.Teacher != username {
		w.WriteJson(message.GetErrorMsg(message.InValidOp, "学生无效"))
		return
	}
	if student.Status == 1 {
		w.WriteJson(message.GetErrorMsg(message.InValidOp, "已审核通过"))
		return
	}
	err := orm.Table("student_info_tbl").Where("id_card = ?", req.Id_card).Update("status", req.Result).Error
	if err != nil {
		w.WriteJson(message.GetErrorMsg(message.UnknownError))
		return
	}
	if req.Result == 1 {
		//自动注入到本系统
		var u user.User_tbl
		u.User = req.Id_card
		_, roles := user.OnGetRoleData([]int{auth_const.R_7})
		u.Business_role = roles
		if user.SaveOneUser(u) {
			//oauth2向注册
			var tmp oauth2.Req_doaction
			tmp.Appid = config.GetRegisterId()
			tmp.Bundleid = common.RECRUIT_TOPIC
			tmp.Flag = 1
			default_password := req.Id_card[len(req.Id_card)-6:] //身份证后6位
			tmp.Password = tools.Md5Encoder(default_password)
			tmp.UserName = req.Id_card
			b = oauth2.OnDoaction(tmp)
			if !b {
				w.WriteJson(message.GetErrorMsg(message.UnknownError))
				return
			}
		}
	}

	w.WriteJson(message.GetSuccessMsg())
}
